package com.banksoft.cps.task;

import com.banksoft.cps.bean.Device;
import com.banksoft.cps.bean.InvokeInfo;
import com.banksoft.cps.bean.SaleOrder;
import com.banksoft.cps.bean.http.request.Request;
import com.banksoft.cps.bean.http.response.BaseData;
import com.banksoft.cps.bean.query.SaleOrderQuery;
import com.banksoft.cps.dao.DeviceDao;
import com.banksoft.cps.dao.InvokeInfoDao;
import com.banksoft.cps.dao.SaleOrderDao;
import com.banksoft.cps.enums.Process;
import com.banksoft.cps.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by rongzhao.zhu on 2018/1/11.
 */
@Service
public class PullDataTask {

    private final int minute_before = 10;

    private final  String url="http://api.tlink.io/tlink_interface/api/device/querySensorDataById_bak.htm";

    @Autowired
    SaleOrderDao saleOrderDao;
    @Autowired
    DeviceDao deviceDao;
    @Autowired
    InvokeInfoDao invokeInfoDao;

    public void execute(){
        /*List<SaleOrder>  saleOrders =  getSaleOrder();
        saleOrders.stream().forEach(s->{
            handle(s);
        });
*/
    }

    /**
     * 获取需要处理的销售单
     * @return
     */
    private List<SaleOrder> getSaleOrder(){
        long  time = DateUtil.getBeforeMinuteTime(System.currentTimeMillis(),minute_before);
        SaleOrderQuery query = new SaleOrderQuery();
        query.setProcess(Process.create.name());
        query.setTimeE(time);
        return saleOrderDao.list(query);
    }

    private void handle(SaleOrder saleOrder){
        Device device = deviceDao.findById(saleOrder.getDeviceId());
        Request request =  PullDataUtil.buildRequest(saleOrder,device);
        request.setPage("1");
        request.setPageSize("1");
        String param =  JsonUtils.encode(request);
        String  result = HttpClientUtil.sendHttpPostJson(url, param);
        BaseData baseData = JsonUtils.decode(result, BaseData.class);
        InvokeInfo invokeInfo  = InvokeInfoBuiler.build("", "",param,url,result);
        invokeInfo.setStatus("ok");
        invokeInfoDao.insert(invokeInfo);
    }



}
